package com.examplemartin.jpademo.controller.admin;


import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.bean.Site;
import com.examplemartin.jpademo.constant.Session_Constant;
import com.examplemartin.jpademo.pojo.admin.OperatorLogPO;
import com.examplemartin.jpademo.pojo.po.MenuPO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.po.sell.SellPO;
import com.examplemartin.jpademo.pojo.po.stock.RepoInfoPO;
import com.examplemartin.jpademo.pojo.vo.MenuVO;
import com.examplemartin.jpademo.service.RepoInfoService;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.admin.OperatorLogService;
import com.examplemartin.jpademo.service.sell.SellService;
import com.examplemartin.jpademo.util.MenuUtil;
import com.examplemartin.jpademo.util.SessionUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys")
@Slf4j
public class SystemControol {

    @Resource
    private Site site;

    @Resource
    private OperatorLogService operatorLogService;

    @Resource
    private UserService userService;

    @GetMapping("/login.do")
    public String Index(Model model) {
        model.addAttribute("site", site);


        return "system/login";

    }

    /**
     * 用户登入  ajax
     *
     * @param username
     * @param password
     * @param capcha
     * @param request
     *
     * @return
     */
    @PostMapping("/login.ajax")
    @ResponseBody
    public AjaxResult login(@RequestParam("username") String username,
                            @RequestParam("password") String password, @RequestParam("capcha") String capcha,
                            HttpServletRequest request
    ) {

        // 校验验证码
        // 1 session 是否拿到
        HttpSession session = request.getSession();
        if (ValidateMember.isEmpty(session)) {
            return AjaxResult.fail(500, "验证吗错误1");
        }
        String vcode = (String) session.getAttribute("vcode");
        // 2 capcha是否拿到
        if (ValidateMember.isEmpty(capcha)) {
            return AjaxResult.fail(500, "请填写验证码2");
        }

        // 3 校验验证码
        if (ValidateMember.isEmpty(vcode) || !capcha.toUpperCase().equals(vcode)) {
            return AjaxResult.fail(500, "验证吗错误3");
        }


        // 登录名是否为空
        if (ValidateMember.isEmpty(username.trim())) {
            return AjaxResult.fail(500, "请填写用户名");
        }
        // 密码是否为空
        if (ValidateMember.isEmpty(password.trim())) {
            return AjaxResult.fail(500, "请填写密码");
        }

        UserPO loginUserPO = userService.login(username.trim(), password.trim());

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        // 用户名或密码 不正确
        if (loginUserPO == null) {
            UserPO adminUserPO = userService.findUserById(1L);

            operatorLogPO.setUser(adminUserPO);
            operatorLogPO.setCreateTime(new Date());
            operatorLogPO.setContent(username + " 尝试登入系统 失败");
            operatorLogService.saveLog(operatorLogPO);


            return AjaxResult.fail(500, "用户名和密码错误");
        }

        // 用户已锁定
        if (loginUserPO.getStatus() == UserPO.USER_STATUS_LOCK) {


            operatorLogPO.setUser(loginUserPO);
            operatorLogPO.setCreateTime(new Date());
            operatorLogPO.setContent("锁定用户:" + loginUserPO.getUsername() + " 尝试登入系统 失败");
            operatorLogService.saveLog(operatorLogPO);


            return AjaxResult.fail(500, "用户被锁定 请联系管理员");
        }

        // 用户角色列表为空
        if (loginUserPO.getRole().getAuthorities().size() <= 0 && !loginUserPO.getRole().getName().equals("supreme")) {
            operatorLogPO.setUser(loginUserPO);
            operatorLogPO.setCreateTime(new Date());
            operatorLogPO.setContent("用户:" + loginUserPO.getUsername() + " 角色 无授权 尝试登入系统 失败");
            operatorLogService.saveLog(operatorLogPO);


            return AjaxResult.fail(500, "用户角色无条目 请联系管理员");
        }


        // 保存session:login-user
        session.setAttribute("loginuser", loginUserPO);
        session.setAttribute("title", site.getTitle());
        // 记录登入操作到日志

        operatorLogPO.setUser(loginUserPO);
        operatorLogPO.setCreateTime(new Date());
        operatorLogPO.setContent("成功登入系统");
        operatorLogService.saveLog(operatorLogPO);


        return AjaxResult.success(200, "success", null);


    }


    @Resource
    private RepoInfoService repoInfoService;

    @Resource
    private SellService sellService;

    /**
     * 进入主页
     *
     * @param page
     * @param model
     *
     * @return
     */
    @GetMapping("/index.do")
    public String index(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page, Model model) {
        String title = "首页";
        model.addAttribute("title", title);
        if (ValidateMember.isEmpty(page) || page == 0) {
            page = 1;
        }

        int pagesize = Integer.parseInt(site.getPageSize());
        if (ValidateMember.isEmpty(pagesize)) {
            pagesize = Integer.MAX_VALUE;
        }
        Pageable pageable = PageRequest.of(page - 1, pagesize, Sort.by("createTime").descending().and(Sort.by("id").descending()));

        List<OperatorLogPO> loglist = operatorLogService.findAllPage(pageable);
        // 计算日志总条数
        Long logSize = operatorLogService.countAll();

        Long totalPage = logSize / pagesize;
        if (totalPage * pagesize < logSize) {
            totalPage++;
        }
        Integer currentPage = page;
        model.addAttribute("loglist", loglist);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);

        // 是否出现 前省略号
        Boolean befor_ellipsis = false;
        if (currentPage >= 4)
            befor_ellipsis = true;
        model.addAttribute("befor_ellipsis", befor_ellipsis);
        // 是否出现 前省略号
        Boolean after_ellipsis = false;
        if ((totalPage - currentPage) > 3)
            after_ellipsis = true;
        model.addAttribute("after_ellipsis", after_ellipsis);

        // b1 -- current -- a1
        // 分页b1 是否出现
        Boolean b1 = false;
        if (currentPage <= 2)
            b1 = true;
        model.addAttribute("b1", b1);
        // 分页a1 是否出现
        Boolean a1 = false;
        if ((totalPage - currentPage) <= 2)
            a1 = true;
        model.addAttribute("a1", a1);
        // 返回最后3页页码
        model.addAttribute("last00", totalPage - 1);
        model.addAttribute("last01", totalPage - 2);
        model.addAttribute("last02", totalPage - 3);
        // 中间页码
        model.addAttribute("mida", currentPage + 1);
        model.addAttribute("midb", totalPage - 1);

        // 中间分页
        Boolean mid = false;
        if (!b1 && !a1) {
            mid = true;
        }
        model.addAttribute("mid", mid);


        log.info("systemContorl.index-loglist.size():" + loglist.size());
        log.info("systemContorl.index-totalPage:" + totalPage);
        log.info("systemContorl.index-currentPage:" + currentPage);

        // 补货信息
        List<RepoInfoPO> byShortage = repoInfoService.findByShortage();
        model.addAttribute("shortagelist",byShortage);

        // 缺货信息
        List<SellPO> outSupply = sellService.findOutSupply();
        model.addAttribute("outsupply",outSupply);

        // 执行中的采购订单
        List<SellPO> runStatus = sellService.findByStatus(SellService.SELL_STATUS_RUNNING);
        model.addAttribute("runningsell",runStatus);

        return "system/index";
    }

    /**
     * 用户注销
     *
     * @param request
     *
     * @return
     */
    @GetMapping("/logout.do")
    public String logout(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        session.removeAttribute("userauthlist");
        session.removeAttribute(Session_Constant.SESSION_LOING_USER_KEY);
        session.invalidate();
        model.addAttribute("site", site);
        return "system/login";

    }

    /**
     * 跳转到日志页面
     */
    @GetMapping("/loglist.do")
    public String logDo(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page, Model model) {
        model.addAttribute("title", "日志管理");


        if (ValidateMember.isEmpty(page) || page == 0) {
            page = 1;
        }

        int pagesize = Integer.parseInt(site.getPageSize());
        if (ValidateMember.isEmpty(pagesize)) {
            pagesize = Integer.MAX_VALUE;
        }
        Pageable pageable = PageRequest.of(page - 1, pagesize, Sort.by("createTime").descending().and(Sort.by("id").descending()));

        List<OperatorLogPO> loglist = operatorLogService.findAllPage(pageable);
        // 计算日志总条数
        Long logSize = operatorLogService.countAll();

        Long totalPage = logSize / pagesize;
        if (totalPage * pagesize < logSize) {
            totalPage++;
        }
        Integer currentPage = page;
        model.addAttribute("loglist", loglist);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);

        // 是否出现 前省略号
        Boolean befor_ellipsis = false;
        if (currentPage >= 4)
            befor_ellipsis = true;
        model.addAttribute("befor_ellipsis", befor_ellipsis);
        // 是否出现 前省略号
        Boolean after_ellipsis = false;
        if ((totalPage - currentPage) > 3)
            after_ellipsis = true;
        model.addAttribute("after_ellipsis", after_ellipsis);

        // b1 -- current -- a1
        // 分页b1 是否出现
        Boolean b1 = false;
        if (currentPage <= 2)
            b1 = true;
        model.addAttribute("b1", b1);
        // 分页a1 是否出现
        Boolean a1 = false;
        if ((totalPage - currentPage) <= 2)
            a1 = true;
        model.addAttribute("a1", a1);
        // 返回最后3页页码
        model.addAttribute("last00", totalPage - 1);
        model.addAttribute("last01", totalPage - 2);
        model.addAttribute("last02", totalPage - 3);
        // 中间页码
        model.addAttribute("mida", currentPage + 1);
        model.addAttribute("midb", totalPage - 1);

        // 中间分页
        Boolean mid = false;
        if (!b1 && !a1) {
            mid = true;
        }
        model.addAttribute("mid", mid);
        return "system/loglist";

    }


    /**
     * 删除日志
     */
    @PostMapping("deletelog.ajax")
    @ResponseBody
    public AjaxResult deletelogAjax(@RequestBody Map<String, List<Long>> map) {

        List<Long> ary = map.get("ary");
        for (Long aLong : ary) {
            operatorLogService.deleteLogById(aLong);
        }

        return AjaxResult.success(200, "成功删除日志: " + ary.size() + " 条", null);
    }

    /**
     * 修改自己的密码
     */
    @GetMapping("/editself.do")
    public String editSelfDo(Model model) {

        UserPO loninUser = SessionUtil.getLoninUser();

        model.addAttribute("title", "密码修改");
        model.addAttribute("userPO", loninUser);

        return "user/editself";
    }

    /**
     * 清空缓存重新加载 用户,菜单列表
     */
    @GetMapping("/flushcache.do")
    public void flushCacheDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());
        HttpSession session = SessionUtil.getsession();
        session.setAttribute(Session_Constant.SESSION_LOING_USER_KEY, loninUser);

        List<MenuPO> authorities = loninUser.getRole().getAuthorities();
        List<MenuVO> authlist = MenuUtil.assembleMenuList(authorities);
        session.setAttribute("userauthlist", authlist);

        request.getRequestDispatcher("/sys/index.do").forward(request, response);
    }

    /**
     * 跳转到帮助界面
     * /sys/helppage.do
     * @param model
     * @return
     */
    @GetMapping("/helppage.do")
    public String helppageDo(Model model){
        model.addAttribute("title","帮助");
        return "system/helppage";

}
}
